// 问卷判断器集合 - 包含各种问卷类型的处理器
import { getQuestionnaire } from './schema-loader.js'
import { extractResultDetailsFromAnswers } from './details-extractor.js'
import { getCompressor } from './compressor.js'
import { generateTags } from './tag-manager.js'
import { saveResults } from './save-results.js'
import { visibilityEngine } from './visibility-engine.js'
import { ScoringEngine } from './scoring-engine.js'
import { storage } from '@/util/storage.js'

/**
 * 处理问卷完成后的导航逻辑
 * @param {string} resultPage - 结果页面配置
 */
const handleNavigation = (resultPage) => {
    if (!resultPage) {
        console.warn('No result_page configured, using default navigation');
        uni.navigateBack();
        return;
    }

    if (resultPage === '$back') {
        // 返回上一页
        uni.navigateBack();
    } else if (resultPage.startsWith('/')) {
        // 导航到指定页面
        uni.redirectTo({
            url: resultPage,
            fail: (err) => {
                console.error('Navigation failed:', err);
            }
        });
    } else {
        console.warn(`Unknown result_page format: ${resultPage}, using default navigation`);
    }
}

/**
 * 问题逻辑引擎 - 处理题目可见性和有效性
 */
export class QuestionLogicEngine {
    constructor(questions, quesName) {
        this.questions = questions;
        this.quesName = quesName;
    }

    /**
     * 获取有效题目ID
     * @param {Array} answers - 当前答案
     * @returns {Array} - 有效题目ID数组
     */
    getValidQuestionIds(answers) {
        const allIds = Array.from({ length: this.questions.length }, (_, i) => i);
        return visibilityEngine.getValidQuestionIds(
            allIds,
            ["visible", "plain"],
            answers,
            this.questions
        );
    }

    /**
     * 获取有效题目和答案
     * @param {Array} answers - 所有答案
     * @returns {Object} - {validQuestions, validAnswers}
     */
    getValidQuestionsAndAnswers(answers) {
        const valid_ids = this.getValidQuestionIds(answers);
        const valid_questions = valid_ids.map((id) => this.questions[id]);
        const valid_answers = valid_ids.map((id) => answers[id]);
        return { valid_questions, valid_answers };
    }
}

/**
 * 问卷判断器 - 主要的问卷处理器
 */
export class QuesJudger {
    constructor({ quesName, handler, globalQues }) {
        this.globalQues = globalQues;
        this.questions = globalQues.questions;
        this.config = { quesName, resultPage: globalQues.result_page };
        this.scoreJudge = globalQues.score_judge;
        this._handler = handler.bind(this);

        // 分离的引擎
        this.scoringEngine = new ScoringEngine(this.scoreJudge, globalQues);
        this.questionLogicEngine = new QuestionLogicEngine(this.questions, quesName);
    }

    /**
     * 处理问卷结果
     * @param {Array} answers - 答案数组
     * @param {Object} eventChannel - 事件通道
     * @returns {*} - 处理结果
     */
    toResult(answers, eventChannel) {
        return this._handler(answers, eventChannel);
    }

    /**
     * 基础处理器 - 计算维度得分
     * @param {Array} answers - 答案数组
     * @returns {Object} - 维度得分对象
     */
    basicHandler(answers) {
        // 使用问题逻辑引擎获取有效题目和答案
        const { valid_questions, valid_answers } = this.questionLogicEngine.getValidQuestionsAndAnswers(answers);

        // 使用评分引擎计算维度得分
        return this.scoringEngine.calculateDimensionScores(valid_questions, valid_answers);
    }

    /**
     * 区间处理器 - 匹配区间结果
     * @param {Array} answers - 答案数组
     * @returns {Object} - 匹配结果后的对象
     */
    intervalHandler(answers) {
        const idToJudge = this.basicHandler(answers);
        console.log("Basic result", idToJudge);

        // 使用评分引擎匹配区间结果
        return this.scoringEngine.matchIntervalResults(idToJudge);
    }
}

/**
 * 创建问卷判断器实例
 * @param {string} quesName - 问卷名称
 * @param {Object} globalQues - 问卷配置
 * @param {Function} handler - 自定义处理器
 * @returns {QuesJudger} - 问卷判断器实例
 */
export const createQuesJudger = (quesName, globalQues, handler) => {
    return new QuesJudger({ quesName, handler, globalQues });
}

/**
 * 创建单个问卷判断器
 * @param {string} quesName - 问卷名称
 * @returns {QuesJudger} - 问卷判断器实例
 */
const createSingleQuesJudger = (quesName) => {
    const questionnaireData = getQuestionnaire(quesName);
    if (!questionnaireData) {
        console.error(`未找到问卷: ${quesName}`);
        return null;
    }

    // 根据问卷类型创建对应的处理器
    switch (quesName) {
        case "screening":
            return createQuesJudger("screening", questionnaireData, function(answers, eventChannel) {
                const idToJudge = this.basicHandler(answers);
                // compare with threshold
                const results = [];
                for (const [key, item] of Object.entries(idToJudge)) {
                    const { content, score } = item;
                    results.push({
                        ...content,
                        score,
                        risk: score > content.threshold,
                    });
                }
                console.log("Screening Result:", results);
                
                let mappedDetails = {};
                try { 
                    mappedDetails = extractResultDetailsFromAnswers(answers, this.questions) || {}; 
                } catch (e) { 
                    console.error('extract details error', e); 
                }
                
                // 上传统一JSON（压缩）
                const compressor = getCompressor('screening');
                // 基于未压缩结果生成 tags
                const tags = generateTags('screening', results);
                const compressed = compressor.compress(results);
                
                // 保存结果
                const currentEventChannel = eventChannel;
                saveResults({
                    type: "screening",
                    result: compressed,
                    tags: tags,
                    details: mappedDetails,
                    success: () => {
                        console.log("Screening results saved successfully");
                        handleNavigation(this.config.resultPage);
                    },
                    fail: (error) => {
                        console.error("Failed to save screening results:", error);
                        // 保存失败时发送事件让用户重新提交
                        currentEventChannel.emit("saveFailed", { error, type: "screening" });
                    }
                });
                
                return results;
            });

        case "a1_cognition":
        case "a2_movement":
        case "a3_nutrition":
        case "a4_vision":
        case "a5_hearing":
        case "a6_emotion":
            return createQuesJudger(quesName, questionnaireData, function(answers, eventChannel) {
                const res = this.intervalHandler(answers);
                
                // 提取详情
                let mappedDetails = {};
                try { 
                    mappedDetails = extractResultDetailsFromAnswers(answers, this.questions) || {}; 
                } catch (e) { 
                    console.error('extract details error', e); 
                }
                
                // 添加总分（从 assess_result.json 读取配置）
                const totalScore = this.scoringEngine.getScoreFigure(this.config.quesName, res);
                if (totalScore) {
                    res['total'] = totalScore;
                }
                
                console.log(`${this.config.quesName} result:`, res);
                
                // 保存结果
                const currentEventChannel = eventChannel;

                const result = {
                    result: res,
                    details: mappedDetails,
                }
                
                // 页面间通信，传递结果和详情
                currentEventChannel.emit("updateAssessRes", result);
                // 保存成功后进行导航
                handleNavigation(this.config.resultPage);
                
                return res;
            });

        case "h1_important_effect":
            return createQuesJudger(quesName, questionnaireData, function(answers, eventChannel) {
                const res = this.intervalHandler(answers);
                
                // 提取详情
                let mappedDetails = {};
                try { 
                    mappedDetails = extractResultDetailsFromAnswers(answers, this.questions) || {}; 
                } catch (e) { 
                    console.error('extract details error', e); 
                }
                
                console.log(`${this.config.quesName} result:`, res);
                
                const result = {
                    result: res,
                    details: mappedDetails
                };
                
                eventChannel.emit("updateAssessRes", result);
                
                handleNavigation(this.config.resultPage);
                
                return result;
            });
            
        case "h2_dangerous_effect":
            return createQuesJudger(quesName, questionnaireData, function(answers, eventChannel) {
                const details = extractResultDetailsFromAnswers(answers, this.questions);
                
                const result = {
                    result: {},
                    details: details
                };
                
                eventChannel.emit("updateAssessRes", result);
                
                handleNavigation(this.config.resultPage);
                
                return result;
            });

        default:
            console.error(`不支持的问卷类型: ${quesName}`);
            return null;
    }
};

/**
 * 获取问卷结果
 * @param {string} quesName - 问卷名称
 * @param {Array} answers - 答案数组
 * @param {Object} eventChannel - 事件通道
 * @returns {*} - 处理结果
 */
export const toResult = (quesName, answers, eventChannel) => {
    const judger = createSingleQuesJudger(quesName);
    if (!judger) {
        console.error(`未找到问卷: ${quesName}`);
        return;
    }
    return judger.toResult(answers, eventChannel);
}
